import requests
import json

# 1.创建会话
url = "https://qianfan.baidubce.com/v2/app/conversation"

payload = json.dumps({
    "app_id": "fe6dce00-1396-4f92-918c-faaabbff2df3"
})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': 'Bearer '
}

response = requests.request("POST", url, headers=headers, data=payload)
# 2.获取会话id
response = json.loads(response.text)
print(response)
conversation_id = response["conversation_id"]



# 4.上传文件（在获取会话id之后，在发送问题之前）
url = "https://qianfan.baidubce.com/v2/app/conversation/file/upload"
payload = {
    'app_id': app_id,
    'conversation_id': conversation_id
}
files = [
    ('file', ('answer.txt', open("answer.txt", 'rb'), 'text/plain'))
]
headers = {
    'X-Appbuilder-Authorization': bearer
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

upload_response_data = json.loads(response.text)

uploaded_file_id = upload_response_data.get('file_id')  # 根据实际响应调整字段名
if uploaded_file_id:
    print("上传成功：", uploaded_file_id)
else:
    print("上传失败")

# 发送问题
url = "https://qianfan.baidubce.com/v2/app/conversation/runs"

payload = json.dumps({
    "app_id": app_id,
    "query": input("请输入问题"),
    "stream": False,
    "conversation_id": conversation_id,
    "file_ids": [+ file_id]

})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': bearer
}

response = requests.request("POST", url, headers=headers, data=payload)
response = json.loads(response.text)
print(response["answer"])


# 3.保存文件
with open("answer.txt",'a',encoding='utf-8') as f:
    f.write(response["answer"])

